<?php

namespace app\airobot\controller;

use app\airobot\CommonLogic;
use app\airobot\model\RobotConfigFileTmp;
use app\airobot\model\RobotProduct;
use think\admin\Controller;
use think\facade\Db;
use think\facade\Log;

/**
 * 超管系统-配置上传
 * Class TestConfigFileUpload
 * @package app\airobot\controller
 */
class TestConfig extends Controller
{
    private $table = 'robot_config_file_tmp';
    public $commonLogic;

    /**
     * 配置上传
     * @auth true
     */
    public function index()
    {
        $this->commonLogic = new CommonLogic();
        $this->title = '配置上传';
        $query = $this->_query($this->table);
        $where = [];
        $query->where($where);
        $query->order('id asc')->page();
    }

    public function import()
    {
        // 保存
        try {
            $adminInfo = $this->app->session->get("user");
            $file = $this->app->request->post('file');
            if (!$file) $this->error('文件不能为空');
            $file = '.' . str_replace("https://box-static.airobot.fund", '', $file);

            // 文件名
            $fileArr = explode("/", $file);
            $fileNameArr = explode("-", $fileArr[count($fileArr) - 1]);
            $fileName = $fileNameArr[count($fileNameArr) - 1];
            if (!in_array($fileName, ['box_rtp.csv', 'forge_rtp.csv', 'box.csv', 'forge.csv', 'product.csv',])) {
                $this->error("文件名不对！");
            }

            // 已经存在同名文件
            $configFileTmpList = Db::table('robot_config_file_tmp')->where(['config_name' => $fileName])->select()->toArray();
            if (count($configFileTmpList) > 0) {
                $this->error("已存在相同配置！");
            }

            // 创建
            $createData = [];
            $createData["manager_id"] = $adminInfo['id'];
            $createData["manager_name"] = $adminInfo['username'];
            $createData["config_name"] = $fileName;
            $createData["config_file"] = $file;
            $robotConfigFileTmp = new RobotConfigFileTmp();
            $robotConfigFileTmp->createInfo($createData);
        } catch (\Exception $e) {
            $this->error("上传失败");
        }

        $this->success('上传成功');
    }

    /**
     * 批量发布
     * @auth true
     */
    public function release()
    {
        try {
            // 开启事务
            Db::startTrans();
            $params = $this->request->post();

            // 查询配置，如果有product配置，让product排前面
            $configFileTmpList = Db::table('robot_config_file_tmp')->whereIn("id", array_values($params['ids']))->select()->toArray();
            $configFileTmpListV2 = [];
            $haveProductConfig = false;
            foreach ($configFileTmpList as $configFileTmp) {
                if ($configFileTmp['config_name'] == "product.csv") {
                    $configFileTmpListV2[] = $configFileTmp;
                    $haveProductConfig = true;
                    break;
                }
            }
            foreach ($configFileTmpList as $configFileTmp) {
                if ($configFileTmp['config_name'] != "product.csv") {
                    $configFileTmpListV2[] = $configFileTmp;
                }
            }
            // 如果没有product配置，则查询数据库
            $configProductMap = [];
            if (!$haveProductConfig) {
                $productModel = new RobotProduct();
                $productList = $productModel->queryList([], [], [], [], [], "", $field = "*", $order = "");
                $configProductMap = array_column($productList, null, 'id');
            }

            // 查询
            foreach ($configFileTmpListV2 as $configFileTmp) {
                // 删除临时记录
                Db::table('robot_config_file_tmp')->where(['config_name' => $configFileTmp['config_name']])->delete();

                // 发布配置：Product
                $configFileUpload = new ConfigFileUpload($this->app);
                if ($configFileTmp['config_name'] == "product.csv") {
                    $configProductMap = $configFileUpload->importProduct($configFileTmp['config_file'], "robot_product");
                }
                // 发布配置：盲盒RTP
                if ($configFileTmp['config_name'] == "box_rtp.csv") {
                    $configFileUpload->importBoxRtp($configFileTmp['config_file'], "robot_box_rtp");
                }
                // 发布配置：Forge-RTP
                if ($configFileTmp['config_name'] == "forge_rtp.csv") {
                    $configFileUpload->importForgeRtp($configFileTmp['config_file'], "robot_forge_rtp");
                }
                // 发布配置：Box
                if ($configFileTmp['config_name'] == "box.csv") {
                    $configFileUpload->importBox($configFileTmp['config_file'], $configProductMap, "robot_box");
                }
                // 发布配置：Forge
                if ($configFileTmp['config_name'] == "forge.csv") {
                    $configFileUpload->importForge($configFileTmp['config_file'], $configProductMap, "robot_forge");
                }
            }

            // 如果一切正常，提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 发生异常时回滚事务
            Log::error("[Release Config Error] error:" . $e->getMessage());
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('发布成功');
    }
}